package top.hkyzf.study.leetcode.tree;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author 朱峰
 * @date 2022-2-19 10:33
 */
public class 二叉树的后序遍历_145 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, result);
        return result;
    }

    private void dfs(TreeNode root, List<Integer> result) {
        if (root == null) {
            return ;
        }
        dfs(root.left, result);
        dfs(root.right, result);
        result.add(root.val);
    }

    /**
     * 方案二：迭代
     * 后序遍历 左右中，因为前序遍历为 中左右，所以先按照 中右左 放入栈，然后统一出栈即可。
     * @param root 根节点
     * @return 遍历结果
     */
    public List<Integer> postorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        if (root == null) {
            return null;
        }
        stack1.push(root);
        while (!stack1.empty()) {
            TreeNode node = stack1.pop();
            stack2.push(node);
            if (node.left != null) {
                stack1.push(node.left);
            }
            if (node.right != null) {
                stack1.push(node.right);
            }
        }
        while (!stack2.empty()) {
            result.add(stack2.pop().val);
        }
        return result;
    }

    @Test
    public void testPostorderTraversal () {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        node1.left = node2;
        root.right = node1;
        System.out.println(postorderTraversal1(root));
    }
}
